<template>
  <!-- 进度条 -->
  <div v-if="isProgress" class="progress">
    <p :style="`width:${percentage}%`"></p>
  </div>
  <!-- 页眉 -->
  <header v-if="pageData.pageHeaderOption" class="page_header">
    <div v-if="pageData.pageHeaderOption.type === 'text'" :style="style">
      {{ pageData.pageHeaderOption.textContent }}
    </div>
    <div v-else>
      <Swipe :autoplay="3000" class="my-swipe" indicator-color="white">
        <SwipeItem
          v-for="(img, k) in pageData.pageHeaderOption.images"
          :key="k"
        >
          <img :src="img.url" alt="" />
        </SwipeItem>
      </Swipe>
    </div>
  </header>
  <!-- 标题和简介 -->
  <div class="enroll_top m15">
    <h2 class="f20 t-center">{{ pageData?.enrollConfig?.enrollName }}</h2>
  </div>
  <!-- 问题区域 -->
  <main
    v-for="(enrollItem, index) in enrollList"
    :key="index"
    class="enroll_item"
  >
    <!-- 移动端 -->
    <div v-if="isMobile">
      <van-form
        v-show="index === newPage"
        @failed="onFailed"
        @submit="onSubmit"
      >
        <van-cell-group class="v_form_group">
          <template v-for="item in enrollItem" :key="item.enrollItemId">
            <component
              :is="dom[item.itemType]"
              v-if="!item.hiddenQuestion && !hideQuestionsWithoutOption(item)"
              :enrollItem="enrollItem"
              :item="item"
              @change="onChange"
            ></component>
          </template>
        </van-cell-group>
        <!-- 按钮区域 -->
        <div class="fixed_btn">
          <div class="err_msg">
            <p v-for="(text, i) in subErrorMsg" :key="i" class="f12 red">
              {{ text }}
            </p>
          </div>
          <div class="btn_flex">
            <van-button
              v-if="enrollList.length > 1 && newPage !== 0"
              block
              class="mr15"
              plain
              type="primary"
              @click="newPage--"
            >上一页
            </van-button>
            <van-button block native-type="submit" type="primary">
              {{ index < enrollList.length - 1 ? "下一页" : "提交" }}
            </van-button>
          </div>
        </div>
      </van-form>
    </div>
    <!-- 电脑端 -->
    <div v-else>
      <ElForm
        v-if="index === newPage"
        ref="ruleFormRef"
        :model="enrollList[index]"
        label-position="top"
      >
        <template
          v-for="(item, childIndex) in enrollItem"
          :key="item.enrollItemId"
        >
          <component
            :is="domPc[item.itemType]"
            v-if="!item.hiddenQuestion && !hideQuestionsWithoutOption(item)"
            :childIndex="childIndex"
            :enrollItem="enrollItem"
            :index="index"
            :item="item"
            @change="onChange"
          ></component>
        </template>
        <div class="m15 mb50 t-center">
          <ElButton
            v-if="enrollList.length > 1 && newPage !== 0"
            class="w100 mr15"
            plain
            type="primary"
            @click="newPage--"
          >
            上一页
          </ElButton>
          <ElButton class="w100" type="primary" @click="submitPc(ruleFormRef)">
            {{ index < enrollList.length - 1 ? "下一页" : "提交" }}
          </ElButton>
        </div>
      </ElForm>
    </div>
  </main>
</template>
<script setup>
import COMPONENTS_h5 from "@/components/components-h5/index";
import COMPONENTS_PC from "@/components/components-pc/index";
import { getDetail } from "@/server/business/enroll.js";
import { commonStore } from "@/stores/common";
import { getUrlQuery } from "@/utils/common.js";
import { handleLogicData, hideQuestionsWithoutOption } from "@/utils/logic";
import { ElButton, ElForm, ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import { closeToast, showLoadingToast, Swipe, SwipeItem } from "vant";
import { computed, inject, onMounted, reactive, ref } from "vue";

const store = commonStore();
const { isMobile } = storeToRefs(store);
const dom = COMPONENTS_h5; // 移动端的组件
const domPc = COMPONENTS_PC; // pc端的组件
const useQuery = getUrlQuery(); // url获取数据
const pageData = reactive({});
const newPage = ref(0); // 当前页码
const enrollList = ref([]); // 分页答题数据 修改此数据 实现页面联动
const enrollIndex = ref(0); // 处理数据的时候用来存放第几页
const metaData = []; // 整理好的元数据
const subErrorMsg = ref([]); // 提交表单报错信息
const ruleFormRef = ref(); // pc端表单
const percentage = ref(0); // 进度条 数值
const isProgress = ref(false); // 进度条 是否展示
const backTop = inject("backTop"); // 返回顶部
const style = computed(() => {
  return {
    fontSize: pageData.pageHeaderOption.font.size + "px",
    color: pageData.pageHeaderOption.font.color,
    fontWeight: pageData.pageHeaderOption.font.bold ? "bold" : "400",
    fontStyle: pageData.pageHeaderOption.font.italic ? "italic" : "initial",
    textDecoration: pageData.pageHeaderOption.font.underline
      ? "underline"
      : "initial",
    textAlign: pageData.pageHeaderOption.font.align,
    background: pageData.pageHeaderOption.font.background,
  };
});

// 值发生变动
const onChange = (event) => {
  // 交互逻辑检测
  handleLogicData(metaData, pageData, event); // 逻辑处理
  handleRenderData(); // 数据从新渲染
  if (isProgress.value) {
    let newList = enrollList.value.flat(2);
    let already = 0;
    let total = newList.length;
    newList.forEach((item) => {
      if (item.value.length > 0) already++;
    });
    percentage.value = (already / total) * 100;
  }
};
// 提交 / 下一页
const onSubmit = () => {
  backTop();
  subErrorMsg.value = [];
  // 整理提交数据后在提交
  if (newPage.value === enrollList.value.length - 1) {
    handleSubmitData();
  } else {
    newPage.value++;
  }
};
// pc 端提交
const submitPc = async (ruleForm) => {
  if (!ruleForm) return;
  ruleForm[0].validate((field) => {
    if (field) onSubmit();
  });
};
// 整理数据 预览页面提交 不能掉真实提交接口
const handleSubmitData = () => {
  let obj = {};
  if (pageData.metaInfo) {
    obj = JSON.parse(pageData.metaInfo);
  }
  if (obj.enrollConfig.afterEvent === "showMessage") {
    ElMessage({ message: "预览页面提交", type: "success" });
  } else if (obj.enrollConfig.afterEvent === "towardPage") {
    if (obj.enrollConfig.towardPage) {
      const reg = /^https?:\/\//i;
      if (reg.test(obj.enrollConfig.towardPage)) {
        // window.open(obj.enrollConfig.towardPage)
        ElMessage({ message: "预览页面提交", type: "success" });
      } else {
        ElMessage({ message: "请输入正确的网址", type: "warning" });
      }
    } else {
      ElMessage({ message: "预览页面提交", type: "success" });
    }
  }
};

// 提交报错信息
const onFailed = (errorInfo) => {
  if (pageData.isOneItemPage === "Y") return;
  subErrorMsg.value = errorInfo.errors.map((item) => item.message);
  console.log("failed", errorInfo);
};
// 获取报名详情
const getEnrollDetail = () => {
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  let params = { get_request: {} };
  if (useQuery.isTemplate === "Y") {
    params.get_request.templateId = useQuery.id;
  } else {
    params.get_request.enrollId = useQuery.id;
  }
  // 模板库-使用模板-预览传enrollId
  if (useQuery.isUseTemplateFirstSave === "false") {
    params = { get_request: { enrollId: useQuery.id } };
  }
  getDetail(params).then(({ data }) => {
    closeToast();
    document.title = data.enrollName || "业务中台";
    Object.assign(pageData, data);
    handleMetaData(data.enrollItemResList);
    isProgress.value = JSON.parse(data.metaInfo)?.formConfig?.showProgress;
  });
};
// 元数据 处理
const handleMetaData = (enrollItemResList) => {
  let types = ["checkbox", "picture-upload", "file-upload", "rate", "slider"];
  enrollItemResList.forEach((item) => {
    const vformJson = JSON.parse(item.vformJson || "{}");
    if (item.itemType === "select") {
      let isMultiple = vformJson.options.isMultiple;
      if (isMultiple && isMobile) item.itemType = "checkbox"; // 下拉选择 开启多选且移动端的时候 直接将类型改成‘多选’
    }
    item.value = types.includes(item.itemType) ? [] : "";
    item.list = [];
    item.itemOptResList = item.itemOptResList.map((itemOpt) => {
      itemOpt.otherValue = null;
      itemOpt.show = ref(true);
      return itemOpt;
    });
    if (item.itemType === "checkbox" || item.itemType === "radio") {
      let lists = [];
      item.itemOptResList.forEach((next) => {
        if (next.isDefault === "Y") lists.push(next.optionName);
      });
      if (lists.length > 0)
        item.value = item.itemType === "radio" ? lists[0] : lists;
    } // 多选,单选 设置默认值
    item.hiddenQuestion = vformJson.options?.hiddenQuestion || false;
    item.orderNum = vformJson.ordNum; // 序号showOrderNum
    item.orderId = vformJson.id;
    item.show = true;
    metaData.push(item);
  });
  handleLogicData(metaData, pageData); // 逻辑处理
  handleRenderData();
};
// 渲染页面的数据处理
const handleRenderData = () => {
  enrollIndex.value = 0;
  enrollList.value = [];
  const obj = pageData.metaInfo ? JSON.parse(pageData.metaInfo) : {}; // 模板库pageData的返回isOneItemPage为空，只在pageData.metaInfo里面有oneItemPage
  metaData.forEach((item) => {
    if (eval(item.show)) {
      if (
        (pageData.enrollConfig &&
          pageData.enrollConfig.isOneItemPage === "Y") ||
        obj.formConfig.oneItemPage
      ) {
        oneQuestionOnePage(item);
      } else {
        handleDefaultData(item);
      }
    }
  });
};
// 一题一页数据处理
const oneQuestionOnePage = (item) => {
  if (item.itemType !== "slicer" && item.itemType !== "divider") {
    enrollList.value[enrollIndex.value] = [];
    // 一页一题，去掉不显示的
    if (!item.hiddenQuestion && !hideQuestionsWithoutOption(item)) {
      enrollList.value[enrollIndex.value].push(item);
      enrollIndex.value++;
    }
  }
};
// 默认处理（非一题一页）
const handleDefaultData = (item) => {
  if (item.itemType !== "slicer") {
    if (!enrollList.value[enrollIndex.value])
      enrollList.value[enrollIndex.value] = [];
    enrollList.value[enrollIndex.value].push(item);
  } else {
    enrollIndex.value++;
  }
};
// 挂载后运行
onMounted(() => {
  getEnrollDetail();
});
</script>
<style lang="less" scoped>
.page_header {
  margin-top: 3px;
}

.submit_loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.enroll_item :deep(.van-field__control--custom) {
  display: block;
}

.my-swipe :deep(.van-swipe-item) {
  color: #fff;
  height: 16rem;
  text-align: center;
  background-color: #39a9ed;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.fixed_btn {
  position: fixed;
  bottom: -1px;
  width: 33rem;
  padding: 1.5rem;
  background: #fff;
  border: none;
  box-shadow: 0 0 1rem var(--van-gray-3);

  .err_msg {
    max-height: 6rem;
    overflow-x: hidden;
    overflow-y: auto;
  }
}

.btn_flex {
  display: flex;
}

.v_form_group {
  padding-bottom: 14rem;
}

.progress {
  position: fixed;
  top: 0;
  width: 100%;
  left: 0;
  z-index: 9999;
  height: 3px;
  margin: 0;
  padding: 0;
  background: #fff;
}

.progress p {
  position: absolute;
  left: 0;
  top: 0;
  margin: 0;
  padding: 0;
  background: var(--el-color-primary);
  height: 3px;
}

.w100 {
  width: 180px;
  padding: 20px;
}
</style>